import BaseAction from '@/components/base/BaseAction';
import BaseButton from '@/components/base/BaseButton';
import { useModal } from '@/components/base/BaseModal';
import BasePageFrame from '@/components/base/BasePageFrame';
import BaseSearch from '@/components/base/BaseSearch';
import BaseTable from '@/components/base/BaseTable';
import { UserModel as User, UserType } from '@/pages/user/data';
import { delUser, delUsers, getUserList } from '@/pages/user/UserInfo/api';
import BindRoleModal from '@/pages/user/UserInfo/modals/BindRoleModal';
import ResetPasswordModal from '@/pages/user/UserInfo/modals/ResetPasswordModal';
import UserInfoModal from '@/pages/user/UserInfo/modals/UserInfoModal';
import { useRequest } from '@/utils/request';
import {
  BlockOutlined,
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
  RetweetOutlined
} from '@ant-design/icons';
import { ActionType, ProColumns } from '@ant-design/pro-table';
import { DatePicker, Space, Tag } from 'antd';
import moment from 'moment';
import { useRef, useState } from 'react';

const UserInfo = () => {
  const tableRef = useRef<ActionType>();
  const userinfoModal = useModal(UserInfoModal, {
    onSuccess() {
      tableRef.current?.reload();
    }
  });
  const resetPasswordModal = useModal(ResetPasswordModal);
  const bindRoleModal = useModal(BindRoleModal);
  const [selectKeys, setSelectKeys] = useState<string[]>([]);
  const del = useRequest(delUser, {
    manual: true,
    fetchKey: (id) => id,
    onSuccess() {
      setSelectKeys([]);
      tableRef.current?.reload();
    }
  });
  const dels = useRequest(delUsers, {
    manual: true,
    onSuccess() {
      setSelectKeys([]);
      tableRef.current?.reload();
    }
  });
  const [searchInfo, setSearchInfo] = useState<{
    createEndDateTime?: string;
    createStartDateTime?: string;
    username?: string;
  }>({});
  const tableColumns: ProColumns<User>[] = [
    {
      dataIndex: 'username',
      title: '用户名'
    },
    {
      dataIndex: 'realName',
      title: '真实姓名'
    },
    {
      dataIndex: 'mobile',
      title: '电话'
    },
    {
      dataIndex: 'mailbox',
      title: '邮箱'
    },
    {
      dataIndex: 'area',
      title: '服务区域',
      renderText: (dom, record) => {
        return record.area?.length > 0 ? (
          <>
            {record.area.map((i) => (
              <Tag key={i.areaId}>{i.areaName}</Tag>
            ))}
          </>
        ) : (
          '-'
        );
      }
    },
    {
      dataIndex: 'certificatesId',
      title: '证件'
    },
    {
      dataIndex: 'userType',
      title: '类别',
      render: (text, record) => <Tag>{UserType.getLabelByValue(record.userType)}</Tag>
    },
    {
      dataIndex: 'jobName',
      title: '职称'
    },
    {
      dataIndex: 'remarks',
      title: '备注'
    },
    {
      title: '操作',
      fixed: 'right',
      render(text, record) {
        return (
          record.username !== 'admin' && (
            <Space>
              <BaseAction
                color='green'
                icon={<EditOutlined />}
                title='编辑'
                code='edit'
                onClick={() => {
                  userinfoModal.load({ data: record });
                }}
              />
              <BaseAction
                code='resetPass'
                color='blue'
                title='重置密码'
                icon={<RetweetOutlined />}
                onClick={() => {
                  resetPasswordModal.load({ userId: record.id });
                }}
              />
              <BaseAction
                code='roleBind'
                title='角色绑定'
                icon={<BlockOutlined />}
                onClick={() => {
                  bindRoleModal.load({ userId: record.id });
                }}
              />
              <BaseAction
                color='red'
                title='删除'
                code='delete'
                icon={<DeleteOutlined />}
                loading={del.fetches[record.id]?.loading}
                onClick={() => {
                  del.run(record.id);
                }}
              />
            </Space>
          )
        );
      }
    }
  ];
  return (
    <BasePageFrame>
      <BaseTable
        rowKey='id'
        actionRef={tableRef}
        request={getUserList}
        columns={tableColumns}
        params={searchInfo}
        headerTitle={
          <BaseButton
            code='create'
            type='primary'
            icon={<PlusOutlined />}
            onClick={() => userinfoModal.load({})}
          >
            新增
          </BaseButton>
        }
        toolBarRender={() => [
          <DatePicker.RangePicker
            style={{ width: 350 }}
            placeholder={['请选择创建开始时间', '请选择创建结束时间']}
            showTime={{ format: 'HH:mm:ss' }}
            format='YYYY-MM-DD HH:mm:ss'
            ranges={{
              今天: [moment().startOf('day'), moment().endOf('day')],
              本月: [moment().startOf('month'), moment().endOf('month')]
            }}
            onChange={(values, dateStrings) => {
              const [createStartDateTime, createEndDateTime] = dateStrings;
              setSearchInfo({
                ...searchInfo,
                createStartDateTime,
                createEndDateTime
              });
            }}
          />,
          <BaseSearch
            defaultValue={searchInfo.username}
            placeholder='请输入用户名或真实姓名搜索'
            style={{ width: 300 }}
            onChange={(v) => {
              setSearchInfo({ ...searchInfo, username: v });
            }}
          />
        ]}
        tableAlertOptionRender={() => (
          <Space size={8}>
            <BaseButton
              type='link'
              disabled={selectKeys.length === 0}
              danger
              icon={<DeleteOutlined />}
              code='delete'
              title='批量删除'
              loading={dels.loading}
              onClick={() => {
                dels.run(selectKeys);
              }}
            >
              批量删除
            </BaseButton>
          </Space>
        )}
        rowSelection={{
          alwaysShowAlert: true,
          preserveSelectedRowKeys: true,
          selectedRowKeys: selectKeys,
          onChange: (keys) => {
            setSelectKeys(keys as string[]);
          }
        }}
      />
    </BasePageFrame>
  );
};

export default UserInfo;
